using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SCSEngine.Utils.Entities.Process.Update
{
    public class UpdateProcessManager : BaseGameProcessManager
    {

        private class UpdateOrderComparer : IComparer<IUpdateable>
        {
            private UpdateOrderComparer()
            {
            }

            public static UpdateOrderComparer Instance { get; private set; }

            static UpdateOrderComparer()
            {
                Instance = new UpdateOrderComparer();
            }

            #region IComparer<IUpdateable> Members

            public int Compare(IUpdateable x, IUpdateable y)
            {
                if (x.UpdateOrder > y.UpdateOrder)
                    return 1;
                else if (x.UpdateOrder == y.UpdateOrder)
                    return 0;

                return -1;
            }

            #endregion
        }

        protected override bool IsValidProcess(object process)
        {
            return (process is IUpdateable);
        }

        public override void Run(Game game, GameTime gameTime)
        {
            List<IUpdateable> updateList = this.Processes.OfType<IUpdateable>().ToList();
            updateList.Sort(UpdateOrderComparer.Instance);

            foreach (IUpdateable updateObject in updateList)
            {
                if (updateObject.Enabled)
                {
                    updateObject.Update(gameTime);
                }
            }
        }

        public override bool IsDrawProcess
        {
            get { return false; }
        }

        public override Type ProcessType
        {
            get { return typeof(IUpdateable); }
        }
    }
}